const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')

class Auth {
  constructor(level) {
    this.level = level || 1
    Auth.USER = 8
    Auth.ADMIN = 16
  }

  get m() {
      return async (ctx, next) => {
        const userToken = basicAuth(ctx.req)
        if (!userToken || !userToken.name) {
          throw new global.errs.Forbidden('userToken不合法')
        }
        try {
          const decode = jwt.verify(userToken.name, 'glnmsl')
          ctx.auth = {
            uid: decode.uid,
            scope: decode.scope
          }
        } catch(error) {
          if (error.name === 'TokenExpiredError') {
            throw new global.errs.Forbidden('userToken已过期')
          }
          throw new global.errs.Forbidden('userToken不合法')
        }

        // 权限验证
        if (ctx.auth.scope < this.level) {
          throw new global.errs.Forbidden('权限不足，无法访问')
        }
        
        await next()
      }
  }

  static verifyToken(token) {
    try {
      jwt.verify(token, 'glnmsl')
      return true
    } catch(error) {
      return false
    }
  }

}

module.exports = Auth